/**
 * 
 */

checkDefaultOptions();

var newTabID;
chrome.tabs.onCreated.addListener(function(tab) {
	newTabID = tab.id;
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	if (tabId == newTabID) {
		for ( var i = 0; i < services.length; i++) {
			checkTab(tab, services[i]);
		}
		newTabID = null;
	}
});

function checkTab(tab, service) {
	if (tab.url.match(service.regex) && isEnabled(service.id)) {
		var newID = tab.id;
		var newUrl = tab.url;
		findTab(service.regex, tab.windowId, newID, function(existingTab) {
			chrome.tabs.remove(newID);
			newTabID = null;
			if (!newUrl.match(service.frontPageRegex)) {
				chrome.tabs.update(existingTab.id, {
					url : newUrl,
					selected : true
				});
			} else {
				chrome.tabs.update(existingTab.id, {
					selected : true
				});
			}
		});
	}
}

function findTab(regexp, winID, apartFromID, callback) {
	chrome.tabs.getAllInWindow(winID, function(tabs) {
		for ( var i = 0; i < tabs.length; i++) {
			if (tabs[i].url.match(regexp) && tabs[i].id != apartFromID) {
				callback(tabs[i]);
				return;
			}
		}
	});
}